package com.xxl.job.admin.core.alarm.impl;

import com.xxl.job.admin.core.alarm.JobAlarm;
import com.xxl.job.admin.core.conf.XxlJobAdminConfig;
import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.model.XxlJobLog;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.core.biz.model.ReturnT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * job alarm by dingding robot
 *
 * @author zhuxuanyong 20240125
 */
@Component
public class RobotJobAlarm implements JobAlarm {
    private static Logger logger = LoggerFactory.getLogger(RobotJobAlarm.class);

    private RestTemplate restTemplate = new RestTemplate();

    /**
     * load root job alarm template
     *
     * @return
     */
    private static final String loadRobotJobAlarmTemplate() {
        String mailBodyTemplate = I18nUtil.getString("jobconf_monitor_detail") + "：\n"
                + I18nUtil.getString("jobinfo_field_jobgroup") + "：{0}\n"
                + I18nUtil.getString("jobinfo_field_id") + "：{1}\n"
                + I18nUtil.getString("jobinfo_field_jobdesc") + "：{2}\n"
                + I18nUtil.getString("jobconf_monitor_alarm_content") + "：{3}";

        return mailBodyTemplate;
    }

    @Override
    public Boolean match(XxlJobInfo info) {
        return info != null && info.getAlarmRobot() != null && !info.getAlarmRobot().trim().isEmpty();
    }

    /**
     * fail alarm
     *
     * @param jobLog
     */
    @Override
    public boolean doAlarm(XxlJobInfo info, XxlJobLog jobLog) {
        boolean alarmResult = true;

        // send monitor robot
        if (info != null && info.getAlarmRobot() != null && !info.getAlarmRobot().trim().isEmpty()) {

            // alarmContent
            String alarmContent = "\nLogId=" + jobLog.getId();
            if (jobLog.getTriggerCode() != ReturnT.SUCCESS_CODE) {
                alarmContent += "<br>" + jobLog.getTriggerMsg();
            }
            if (jobLog.getHandleCode() > 0 && jobLog.getHandleCode() != ReturnT.SUCCESS_CODE) {
                alarmContent += "<br>" + jobLog.getHandleMsg();
            }
            alarmContent = alarmContent.replaceAll("<br>", "\n");

            // root info
            XxlJobGroup group = XxlJobAdminConfig.getAdminConfig().getXxlJobGroupDao().load(Integer.valueOf(info.getJobGroup()));
            String content = MessageFormat.format(loadRobotJobAlarmTemplate(), group != null ? group.getTitle() : "null", info.getId(), info.getJobDesc(), alarmContent);

            Set<String> robotSet = new HashSet<>(Arrays.asList(info.getAlarmRobot().split(",")));

            for (String robot : robotSet) {
                try {
                    // 钉钉机器人
                    if (robot.startsWith("https://oapi.dingtalk.com")) {
                        String str = "{'msgtype': 'text','text': {'content':'" + content + "'}}";

                        HttpHeaders headers = new HttpHeaders();
                        headers.setContentType(MediaType.APPLICATION_JSON);
                        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

                        HttpEntity<String> request = new HttpEntity<>(str, headers);
                        restTemplate.postForEntity(robot, request, String.class);
                    }
                } catch (Exception e) {
                    logger.error(">>>>>>>>>>> xxl-job, job fail alarm robot send error, JobLogId:{}", jobLog.getId(), e);

                    alarmResult = false;
                }
            }
        }
        return alarmResult;
    }

}
